package org.xiaoken.wechat.robot.util;

import com.alibaba.fastjson.JSONObject;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板加载工具
 *
 * @author guokenye
 */
public class TemplateUtil {

    private static final Map<String, Template> CACHE = new HashMap<>();

    private static Configuration configuration;

    public static void setConfiguration(Configuration configuration) {
        TemplateUtil.configuration = configuration;
    }

    public static Template getTemplate(String templateName) throws IOException {
        if (!CACHE.containsKey(templateName)) {
            CACHE.put(templateName, configuration.getTemplate(templateName));
        }
        return CACHE.get(templateName);
    }

    public static String renderTemplate(String templateName, Object param) throws IOException, TemplateException {
        String jsonStr = JSONObject.toJSONString(param);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        return renderTemplate(templateName, jsonObject);
    }


    public static String renderTemplate(String templateName, Map<String, Object> param) throws IOException, TemplateException {
        return FreeMarkerTemplateUtils.processTemplateIntoString(getTemplate(templateName), param);
    }


}
